package cn.csq.rpc;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Objects;

/**
 * @author csq
 * @version 1.0.0
 * @ClassName ServiceDescriptor.java
 * @Description 表示服务
 * @createTime 2021年12月19日 21:26:00
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ServiceDescriptor {

    /**
     * 类名
     */
    private String clazz;
    /**
     * 方法名
     */
    private String method;

    /**
     * 返回类型
     */
    private String returnType;
    /**
     * 参数列表
     */
    private String[] parameterTypes;

    /**
     * 将提供服务的类和方法 转为服务描述信息
     * @param clazz
     * @param method
     * @return
     */
    public static ServiceDescriptor from(Class clazz, Method method) {
        ServiceDescriptor serviceDescriptor = new ServiceDescriptor();
        serviceDescriptor.setClazz(clazz.getName());
        serviceDescriptor.setMethod(method.getName());
        serviceDescriptor.setReturnType(method.getReturnType().getName());
        Class<?>[] parameterClasses = method.getParameterTypes();
        String[] parameterTypes = new String[parameterClasses.length];
        for (int i = 0; i < parameterClasses.length; i++) {
            parameterTypes[i] = parameterClasses[i].getName();
        }
        serviceDescriptor.setParameterTypes(parameterTypes);
        return serviceDescriptor;
    }

    @Override
    public boolean equals(Object o) {
        if (this==o) return  true;
        if (o==null||getClass() != o.getClass())return false;

        ServiceDescriptor serviceDescriptor = (ServiceDescriptor) o;
        return this.toString().equals(serviceDescriptor.toString());
    }

    @Override
    public int hashCode() {
        return toString().hashCode();
    }

    @Override
    public String toString() {
        return "clazz=" + clazz
                + ",method=" + method
                + ",returnType=" + returnType
                + ",parameterTypes=" + Arrays.toString(parameterTypes);
    }
}
